from flask import abort
from flask import current_app
from flask import g
from flask import redirect, jsonify
from flask import render_template
from flask import request

from info import constants, db
from info.models import Category, News, User
from info.modules.profile import profile_blu
from info.utlis.common import user_login_data
from info.utlis.image_storage import storage
from info.utlis.response_code import RET


#TODO 其他用户界面新闻类表显示
@profile_blu.route('/other_news_list')
@user_login_data
def other_news_list():
    #获取参数 从other.js中获取
    other_id = request.args.get('other_id')
    page = request.args.get("p",1)
    try:
        p = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # sss
    if not all([p, other_id]):
        # 1111

        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not other:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    try:
        # paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        paginate = other.news_list.paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []
    for news_item in news_li:
        news_dict_li.append(news_item.to_basic_dict())


    data = {"news_list": news_dict_li,
            "total_page": total_page,
            "current_page": current_page}
    return jsonify(errno=RET.OK, errmsg="OK", data=data)







#TODO 其他用户界面的显示
@profile_blu.route('/other_info')
@user_login_data
def other_info():
    user = g.user

    #获取参数
    other_id = request.args.get('other_id')
    if not other_id:
        abort(404)

    #查询指定id的用户信息
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)


    data = {
        'user':user.to_dict(),
        "other_info":other.to_dict()
    }
    return render_template('news/other.html',data=data)



#TODO 个人中心我的关注的路由
@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    # 获取参数
    page = request.args.get("p", 1)

    # 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user = g.user
    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(page, constants.USER_FOLLOWED_MAX_COUNT, False)
        follows = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []
    for users in follows:
        user_dict_li.append(users.to_dict())

    data = {"users": user_dict_li,
            "total_page": total_page,
            "current_page": current_page}

    return render_template('news/user_follow.html', data=data)



#TODO 新闻列表的路由

@profile_blu.route('/news_list')
@user_login_data
def user_news_list():

    # 获取参数
    page = request.args.get("p", 1)


    # 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user = g.user
    news_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id==user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_review_dict())

    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page,
    }

    return render_template('news/user_news_list.html', data=data)


#TODO 我的收藏的路由
@profile_blu.route('/collection')
@user_login_data
def user_collection():
    #获取当前页数
    p = request.args.get('p',1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        #设置默认
        p = 1
    user = g.user
    collections = []
    current_page = 1#当前页数
    total_page =1#总页数

    try:
        #查询分页数据
        paginate = user.collection_news.paginate(p,constants.USER_COLLECTION_MAX_NEWS)
        #获取总也数
        total_page = paginate.pages
        #获取当前页数
        current_page = paginate.page
        # 获取分页数据
        collections = paginate.items
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保查询失败")

    #定义收藏字典列表
    collection_dict_li = []
    for news in collections:
        collection_dict_li.append(news.to_basic_dict())

    data = {"total_page": total_page,
            "current_page": current_page,
            "collections": collection_dict_li}
    return render_template('news/user_collection.html', data=data)


#TODO 新闻发布的路由
@profile_blu.route('/news_release', methods=["GET", "POST"])
@user_login_data
def news_release():
    #加载新闻的数据
    #判断是否是get请求：
    if request.method == "GET":
        categories = []
        try:
            #查询出所有分类对象 保存在列表
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
        #遍历对象列表 转换成字典添加到列表中
        category_dict_li = []
        for category in categories:
            category_dict_li.append(category.to_dict())
        #移除最新的分类
        category_dict_li.pop(0)
        return render_template('news/user_news_release.html',data={"categories":category_dict_li})

    #post请求
    #获取提交的数据
    title = request.form.get("title")
    # 新闻来源
    source = "个人发布"
    # 摘要
    digest = request.form.get("digest")
    # 新闻内容
    content = request.form.get("content")
    # 索引图片
    index_image = request.files.get("index_image")
    # 分类id
    category_id = request.form.get("category_id")

    #校验参数
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    #校验页数类型
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="参数错误")

    #取到图片将图片上传到七牛云
    try:
        index_image_data =index_image.read()
        #将图片上传
        key = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据有误")

    #创建模型 更新数据
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表待审核状态
    news.status = 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    return jsonify(errno=RET.OK, errmsg="OK")


#*********************************************************************************************************
# TODO 密码更改的路由
@profile_blu.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    if request.method=="GET":
        return render_template('news/user_pass_info.html')

    #获取参数
    data_dict =request.json
    old_password = data_dict.get('old_password')
    new_password = data_dict.get('new_password')
    #判断是我否有数据
    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="数据不全")

    #获取用户信息
    user = g.users
    #判断旧密码输入的是否正确
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码不正确")
    #更新数据
    user.password = new_password
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    return jsonify(errno=RET.OK, errmsg="OK")



#************************************************************************************************

#TODO 更换头像的路由
@profile_blu.route('/pic_info', methods=["GET", "POST"])
@user_login_data
def pic_info():
    user = g.user
    # 不同的请求方式，做不同的事情
    if request.method == "GET":
        return render_template('news/user_pic_info.html', data={"user": g.user.to_dict()})

    #上传头像的实现
    #1取到上传的图片
    try:
        avatar = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    #2上传头像
    try:
        key = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")


    #3保存头像的地址
    user.avatar_url = key
    return jsonify(errno=RET.OK, errmsg="OK",data ={"avatar_url":constants.QINIU_DOMIN_PREFIX+key})

#***************************************************************************************************

#TODO 请求个人中心的路由 和修改基本资料
@profile_blu.route('/base_info', methods=["GET", "POST"])
@user_login_data
def base_info():
    # 不同的请求方式，做不同的事情
    if request.method == "GET":
        return render_template('news/user_base_info.html', data={"user": g.user.to_dict()})

    # 代表是修改用户数据
    # 1. 取到传入的参数
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")

    # 2. 校验参数
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if gender not in ("WOMAN", "MAN"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    user = g.user
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender

    return jsonify(errno=RET.OK, errmsg="OK")

#请求个人中心主页
@profile_blu.route('/info')
@user_login_data
def user_info():
    user = g.user
    if not user:
        # 代表没有登录，重定向到首页
        return redirect("/")
    data = {"user": user.to_dict()}
    return render_template('news/user.html', data=data)